#include <iostream>
#include <string.h>

#include "sha1.hpp"
#include "base64.hpp"
#include "hmac.hpp"
#include "md5.hpp"

using namespace crypto;

void binary_2_hex(const std::string & binary, std::string & hex_str)
{
	const char HEX[] = "0123456789ABCDEF";
	std::string::const_iterator iter = binary.begin(); 
	for (; iter != binary.end(); ++ iter)
	{
		hex_str += HEX[(*iter) & 0xf];
		hex_str += HEX[((*iter) >> 4) & 0xf];
	}
}

void hex_2_binary(const std::string & hex_str, std::string & binary)
{
#define HEX_2_INT(h) ((h >= '0' && h <= '9')? (h - '0'): (h - 'A' + 10))

	if (0 != (hex_str.size() & 1))
	{
		std::cout << "mod 2 != 0" << std::endl;
		return;
	}
	std::string::const_iterator iter = hex_str.begin(); 
	for (; iter != hex_str.end();)
	{
		char c1 = *iter ++;
		char c2 = *iter ++;

		binary += (char)((HEX_2_INT(c2) << 4) | HEX_2_INT(c1));
	}
#undef HEX_2_INT
}

int main(int argc, char * argv[])
{
	const char * key = "228bf094169a40a3bd188ba37ebe8723&";
	const char * in  = "GET&%2Fv3%2Fuser%2Fget_info&appid%3D123456%26openid%3D11111111111111111%26openkey%3D2222222222222222%26pf%3Dzone";
	
	const char * key = "228bf094169a40a3bd188ba37ebe8723&";
	const char * in  = "GET&%2Fv3%2Fuser%2Fget_info&appid%3D123456%26openid%3D11111111111111111%26openkey%3D2222222222222222%26pf%3Dqzone";

	std::string resstr;

	Hmac::sha1((void*)key, strlen(key), (void*)in, strlen(in), resstr);

	std::string out;

	if (Base64::encode(resstr.c_str(), resstr.size(), out))
	{
		std::cout << "Base64: " << out << std::endl;
	}
	else
	{
		std::cout << "fail" << std::endl;
	}

#if 0
	std::string binary("Hello World");
	std::string hex_str;

	binary_2_hex(binary, hex_str);

	std::cout << hex_str << std::endl;

	std::string binary2;
	hex_2_binary(hex_str, binary2);

	std::cout << binary2 << std::endl;
#endif
	return 0;
}

